package com.ayuer.chapter05;


import java.util.Iterator;


/**
 * 基于双向链表实现双端队列
 *
 * @param <E>
 */
public class LinkedListDeque<E> implements Deque<E>, Iterable<E> {

    static class Node<E> {
        E data;
        Node<E> prev;

        Node<E> next;

        public Node(E data, Node<E> prev, Node<E> next) {
            this.data = data;
            this.next = next;
            this.prev = prev;
        }
    }

    int capacity;

    int size;

    Node<E> sentinel = new Node<E>(null, null, null);

    public LinkedListDeque(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        //初始化哨兵
        sentinel.next = sentinel;
        sentinel.prev = sentinel;
    }


    @Override
    public boolean offerFirst(E e) {
        if (isFull()) {
            return false;
        }
        Node<E> a = sentinel;
        Node<E> b = sentinel.next;
        Node<E> newNode = new Node<E>(e, a, b);
        a.next = newNode;
        b.prev = newNode;
        size++;
        return true;
    }

    @Override
    public boolean offerLast(E e) {
        if (isFull()) {
            return false;
        }
        //尾节点
        Node<E> a = sentinel.prev;
        Node<E> newNode = new Node<E>(e, a, sentinel);
        a.next = newNode;
        a.prev = newNode;
        size++;
        return true;
    }

    @Override
    public E pollFirst() {
        if (isEmpty()) {
            return null;
        }
        
        return null;
    }

    @Override
    public E pollLast() {
        return null;
    }

    @Override
    public E peekFirst() {
        return null;
    }

    @Override
    public E peekLast() {
        return null;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {

        return new Iterator<E>() {

            Node<E> p = sentinel.next;

            @Override
            public boolean hasNext() {
                return p != sentinel;
            }

            @Override
            public E next() {
                E data = p.data;
                p = p.next;
                return data;
            }
        };
    }
}
